<?php
/*
  PHP version 5
  Copyright (c) 2002-2010 ECISP.CN
  声明：这不是一个免费的软件，请在许可范围内使用

  作者：Bili E-mail:huangqyun@163.com  QQ:6326420
  http://www.ecisp.cn	http://www.easysitepm.com
 */

class mainpage extends connector {

	function mainpage() {
		$this->softbase(false);
		$this->mlink = $this->memberlink(array(), admin_LNG);
	}

	function in_list() {
		parent::start_pagetemplate();
		$lng = (admin_LNG == 'big5') ? $this->CON['is_lancode'] : admin_LNG;
		$cartid = $this->fun->accept('ecisp_order_list', 'C');
		$cartid = stripslashes(htmlspecialchars_decode($cartid));
		$uncartid = !empty($cartid) ? unserialize($cartid) : 0;
		if ($uncartid && is_array($uncartid)) {
			$didarray = $this->fun->key_array_name($uncartid, 'did', 'amount');
			$didlist = $this->fun->format_array_text(array_keys($didarray), ',');
			if (!empty($didlist)) {
				$db_table = db_prefix . 'document';
				$db_where = "isclass=1 AND isorder=1 AND did in($didlist) ORDER BY did DESC";
				$sql = "SELECT did,lng,pid,mid,aid,tid,sid,fgid,linkdid,isclass,islink,ishtml,ismess,isorder,purview,recommend,tsn,title,longtitle,
					color,author,source,pic,link,oprice,bprice,click,addtime,template,filename,filepath FROM $db_table WHERE $db_where";
				$rs = $this->db->query($sql);

				$productmoney = 0;
				while ($rsList = $this->db->fetch_assoc($rs)) {
					$rsList['link'] = $this->get_link('doc', $rsList, admin_LNG);
					$rsList['buylink'] = $this->get_link('buylink', $rsList, admin_LNG);
					$rsList['enqlink'] = $this->get_link('enqlink', $rsList, admin_LNG);

					$rsList['dellink'] = $this->get_link('buydel', $rsList, admin_LNG);
					$rsList['ctitle'] = empty($rsList['color']) ? $rsList['title'] : "<font color='" . $rsList['color'] . "'>" . $rsList['title'] . "</font>";
					$rsList['amount'] = $didarray[$rsList['did']];

					$countprice = sprintf("%01.2f", $didarray[$rsList['did']] * $rsList['bprice']);
					$rsList['countprice'] = $countprice;

					$productmoney = $productmoney + $countprice;
					$array[] = $rsList;
				}

				$this->fun->setcookie('ecisp_order_productmoney', $productmoney, 7200);
			}

			$this->pagetemplate->assign('ordertotal', number_format($productmoney, 2));
			$this->pagetemplate->assign('array', $array);
			$this->pagetemplate->assign('moneytype', $this->CON['order_moneytype']);
		} else {
			$this->pagetemplate->assign('ordervirtue', 'false');
		}
		$this->pagetemplate->assign('mlink', $this->mlink);

		$templatesDIR = $this->get_templatesdir('order');
		$this->pagetemplate->assign('path', 'order');
		$templatefilename = $lng . '/' . $templatesDIR . '/order_buy_center';
		$this->pagetemplate->assign('out', 'buylist');
		unset($array, $this->mlink, $LANPACK, $this->lng);
		$this->pagetemplate->display($templatefilename, 'order_list', false, '', admin_LNG);
	}

	function in_buy() {
		$did = intval($this->fun->accept('did', 'G'));
		if (empty($did)) trigger_error("Parameter error!", E_USER_ERROR);
		$db_table = db_prefix . 'document';
		$db_sql = "SELECT did,tsn,title,oprice,bprice FROM $db_table WHERE isclass=1 AND did=$did AND isorder=1";
		$readdid = $this->db->fetch_first($db_sql);
		if ($readdid) {

			$cartid = $this->fun->accept('ecisp_order_list', 'C');
			$cartid = stripslashes(htmlspecialchars_decode($cartid));

			$arraykeyname = 'k' . $did;

			if (empty($cartid) || strlen($cartid) < 7) {

				$orderlist = array($arraykeyname => array('did' => $did, 'amount' => 1));
				$orderlist = serialize($orderlist);
			} else {
				$orderid = unserialize($cartid);

				if (is_array($orderid) && array_key_exists($arraykeyname, $orderid)) {

					$amount = $orderid[$arraykeyname]['amount'] + 1;

					unset($orderid[$arraykeyname]);
					$nowcart = array($arraykeyname => array('did' => $did, 'amount' => $amount));
					$newcart = array_merge($orderid, $nowcart);
					$orderlist = serialize($newcart);
				} elseif (is_array($orderid)) {

					$nowcart = array($arraykeyname => array('did' => $did, 'amount' => 1));
					$newcart = array_merge_recursive($nowcart, $orderid);
					$orderlist = serialize($newcart);
				} else {
					$nowcart = array($arraykeyname => array('did' => $did, 'amount' => 1));
					$orderlist = serialize($newcart);
				}
			}
			$this->fun->setcookie('ecisp_order_list', $orderlist, 7200);
			$buylink = $this->get_link('order', array(), admin_LNG);
			$linkURL = $_SERVER['HTTP_REFERER'];
			$this->callmessage($this->lng['order_buy_ok'], $linkURL, $this->lng['oder_buy_goback'], 1, $this->lng['order_buy_listbotton'], 1, $buylink);
		} else {
			$linkURL = $_SERVER['HTTP_REFERER'];
			$this->callmessage($this->lng['order_buy_err'], $linkURL, $this->lng['gobackbotton']);
		}
	}
	//订单页面
	function in_hotelorder() {
		parent::start_pagetemplate();
		
		$check = parent::member_purview_ajax(1, null, true);
		$username = $this->ec_member_username;
		$uid = $this->ec_member_username_id;
		$user = array();
		if($uid && $username) {
			$coo = $this->fun->eccode($_COOKIE['ecisp_member_info'], 'DECODE', db_pscode);
			$arruser = explode('|',$coo);
			$nickname = $arruser[1];
			$useremail = $arruser[4];
			$userphone = $_COOKIE['ydb_member_username'];
			
			$user = array('nickname'=>$nickname,'email'=>$useremail,'username'=>$userphone);
		}
		
		$lng = (admin_LNG == 'big5') ? $this->CON['is_lancode'] : admin_LNG;
		$hotelCode = $this->fun->accept('hid', 'R'); 
		$roomCode = $this->fun->accept('rid', 'R'); 
		$roomRatePlan = $this->fun->accept('pid', 'R'); 
		$checkInDate = $this->fun->accept('tm1', 'R'); 
		if(!$checkInDate) { $checkInDate = $this->fun->accept('ordertm1', 'R');}
		$checkOutDate = $this->fun->accept('tm2', 'R'); 
		if(!$checkOutDate) { $checkOutDate = $this->fun->accept('ordertm2', 'R');}
		$roomCount = $this->fun->accept('roomnum', 'R'); 
		$arriveTime = $this->fun->accept('arriveTime', 'R');
		if(!$roomCount) {$roomCount=1;}
		$bookingDate = time();
		
		$arr = $info = array();
		$arr = $this->get_hotel_0rderroomstatus($hotelCode,$roomCode,$roomRatePlan,$checkInDate,$checkOutDate);
		if($arr['Status'] == 0) {
			$arr = $arr['ResponseBody'];
		} else {
			$this->fun->message($arr['Messages'][0]);
		}
		$hotelinfo = $arr; $hotelinfo['GaranteeRules'] = null;
		include_once admin_ROOT . 'public/class_json.php';
		
		$isjson = function_exists('json_decode')? true : false;
		$jsoninfo = "";
		if($isjson) {
			$jsoninfo = json_encode($hotelinfo);
		} else {
			$json = new json();
			$jsoninfo = $json->jsonEncode($hotelinfo);
		}
		$param = array(
			'hotelCode' => $hotelCode,
			'roomCode'  => $roomCode,
			'roomRatePlan' => $roomRatePlan,
			'checkInDate' => $checkInDate,
			'checkOutDate' => $checkOutDate,
			'roomCount' => $roomCount
		);
		
		$arrhotel =  $arr['Hotel'];  $arrhotel['Rooms'] = null;
		$arrrooms = $arr['Hotel']['Rooms'];
		$info = array(); $GaranteeRules = array(); $Rates = array();
		foreach ($arrrooms as $key=>$value) {
			if($value['TypeId'] == $param['roomCode']) {
				$info['Name'] = $value['Name'];
				$info['BedDescription'] = $value['BedDescription'];
				$info['Area'] = $value['Area'];
				$info['Broadband'] = $value['Broadband'];
				$info['AveragePrice'] = $value['RatePlans'][0]['AveragePrice'];
				$info['RatePlans'] = $value['RatePlans'][0]['Name'];
				$info['Note'] = str_replace("免费","",$value['Note']).";房间面积：".$value['Area']."平方米;楼层：".$value['Floor']."层；说明：".$info['RatePlans'];
				$GaranteeRules = $value['RatePlans'][0]['GaranteeRules'];  //担保规则
				$Rates = $value['RatePlans'][0]['Rates'];
			}
		}
		$i = 0; $str = "<tr class=\"title\">"; $t = $p = ''; $c = count($Rates); $firstNightFees = 0; $fullyFees = 0;
		foreach ($Rates as $key=>$d) {
			if($d['CanBook'] == false) {
				$price = "<font color='#575757'>满房</font>";
			} else {
				$price = "¥".$d['MemberRate'];
			}
			$t .= "<td>".date('m月d日',$d['Date'])."(".$this->fun->format_week($d['Date']).")</td>";
			$p .= "<td><span class='zc'><font color='#e46b11'>".$price."</font></span><br />".$info['RatePlans']."</td>";
			$fullyFees += intval($d['MemberRate']);
			$i++;
			if($i == 1) {
				$firstNightFees = $d['MemberRate'];
			}
			if(fmod($i,6) == 0 || $i == $c) {
				$str .= $t . "</tr><tr>" . $p . "</tr>";
				if($i<$c) { $str .= "<tr class=\"title\">"; }
				$t = $p = "";
			}
		}
		$rule = $GaranteeRules;  $arrive = array();
		if($rule) {
			$Deposit = $rule[0]['Deposit'];
			$ArriveStartTime = $rule[0]['ArriveStartTime'];
			$ArriveEndTime = $rule[0]['ArriveEndTime'];
			$arrive = array('ArriveStartTime'=>date('H:i',$ArriveStartTime),'ArriveStartTime2'=>(date('H',$ArriveStartTime).":05"),'ArriveEndTime'=>date('H:i',$ArriveEndTime));
			$arriveTime = $arrive['ArriveStartTime'];
		}
		if(!$rule) {
			$thisrule = '';
		} else {
			$thisrule = $rule;
		}
		if(!$arriveTime) { $arriveTime = "18:00";}
		if($isjson) {
			$jsonrule = json_encode($rule);
		} else {
			$json = new json();
			$jsonrule = $json->jsonEncode($rule);
		}
		$allfullyFees = $fullyFees * intval($roomCount);   //总价格
		
		$checkguarantee = '';
		$logined = "no";
		$check = parent::member_purview_ajax(1, null, true);
		$username = $this->ec_member_username;
		$uid = $this->ec_member_username_id;
		if($uid && $username) {
			$logined = "ok";
		}
		$Integral = 0;
		if($this->CON['mem_isintegral']) {
			$keyfee = 0;
			if($this->CON['mem_selintegral']==1) { //1  按比例  0 按订单积分
				$keyfee = $this->CON['member_ishotelpercent'];  //比例数
				$Integral = round($allfullyFees * $keyfee /100);
			} else {
				$keyfee = $this->CON['member_ishotelorder'];  //每个酒店订单积分
				$Integral = $keyfee;
			}
		}
		$var_integral = $this->CON['mem_isintegral']."|".$this->CON['mem_selintegral']."|".$this->CON['member_ishotelorder']."|".$this->CON['member_ishotelpercent'];
		
		//$checkguarantee = $this->getgaranteerule($rule, $bookingDate, strtotime($checkInDate), $arriveTime, $roomCount, $firstNightFees, $fullyFees);
		$linkurl = $this->get_link("hotel_orderlist",$param,$lng);
		$hotelurl = $this->get_link('hotelshow',array('hid'=>$hotelCode),$lng);
		$this->pagetemplate->assign('array', $arrhotel);
		$this->pagetemplate->assign('rooms', $info);
		$this->pagetemplate->assign('varintegral', $var_integral); //积分规则
		$this->pagetemplate->assign('mem_isintegral', $this->CON['mem_isintegral']);
		$this->pagetemplate->assign('integral', $Integral);
		$this->pagetemplate->assign('user', $user);
		$this->pagetemplate->assign('param', $param);
		$this->pagetemplate->assign('checkguarantee', $checkguarantee);  //担保信息
		$this->pagetemplate->assign('ordertoken', $arr['OrderToken']);
		$this->pagetemplate->assign('rates', $str);
		$this->pagetemplate->assign('logined', $logined);
		$this->pagetemplate->assign('rule', $thisrule);
		$this->pagetemplate->assign('fullfees', $fullyFees);
		$this->pagetemplate->assign('firstNightFees', $firstNightFees);
		$this->pagetemplate->assign('allfullyFees', $allfullyFees);
		$this->pagetemplate->assign('jsonrule', $jsonrule);
		$this->pagetemplate->assign('Deposit', $Deposit);
		$this->pagetemplate->assign('arrive', $arrive);
		$this->pagetemplate->assign('linkurl', $linkurl);
		$this->pagetemplate->assign('hotelurl', $hotelurl);
		$this->pagetemplate->assign('jsoninfo', $jsoninfo);
		
		$templatesDIR = $this->get_templatesdir('hotel');
		$templatefilename = $templatecache = "";
		$templatefilename = $lng . '/' . $templatesDIR . '/hotel_order';
		$templatecache = "hotel_order";
		unset($arr,$arrhotel,$info,$param);
		$this->pagetemplate->display($templatefilename, $templatecache, false, '', admin_LNG);
	}
	//订单保存
	function in_hotelordersave() {
		$re = $resubmit = array();
		$hotelCode       = 	$this->fun->accept('hid', 'R');
		$roomCode        = 	$this->fun->accept('rid', 'R');
		$roomRatePlan    = 	$this->fun->accept('pid', 'R');
		$checkInDate     = 	$this->fun->accept('tm1', 'R');
		$checkOutDate    = 	$this->fun->accept('tm2', 'R');
		$arrivalEarlyTime=  $this->fun->accept('arrivalEarlyTime', 'R');
		$arrivalLateTime = 	$this->fun->accept('arrivalLateTime', 'R');
		$note            = 	$this->fun->accept('note', 'R');
		$roomCount       = 	$this->fun->accept('roomnum', 'R');
		$allfullfees     =  $this->fun->accept('allfullfees', 'R');
		$firstNightFees  =  $this->fun->accept('firstNightFees', 'R');
		$guest           = 	$this->fun->accept('guestname', 'R');
		$contacterName   = 	$this->fun->accept('contactname', 'R');
		$reg             = 	$this->fun->accept('reg', 'R');
		$contacterMobile = 	$this->fun->accept('contactmobile', 'R');
		$contacterEMail  = 	$this->fun->accept('contactemail', 'R');
		$ischeckguarantee = $this->fun->accept('ischeckguarantee', 'R');
		$isGuaranteeable = false;
		if($ischeckguarantee == "yes") {
			$isGuaranteeable = true;
		} else {
			$isGuaranteeable = false;
		}
		$ccHolderName    = 	$this->fun->accept('pu_name', 'R');  //持卡人姓名
		$ccNumber        = 	$this->fun->accept('pu_cardno', 'R');  //信用卡卡号
		$ccValidYear     = 	$this->fun->accept('pu_year', 'R'); //年
		$ccValidMonth    = 	$this->fun->accept('pu_month', 'R'); //月
		$ccVeryfyCode    = 	$this->fun->accept('pu_code', 'R'); //CVV2码 3位
		$ccIdTypeCode    = 	$this->fun->accept('pu_idtype', 'R');  //证件类型
		$ccIdNumber      = 	$this->fun->accept('pu_idno', 'R'); //证件号
		$hotelinfo = $dbparam = array();
		$hinfo       =  stripslashes(html_entity_decode($this->fun->accept('hotelinfo', 'R')));
		include_once admin_ROOT . 'public/class_json.php';
		$isjson = function_exists('json_decode')? true : false;
		if($isjson) {
			$hotelinfo = json_decode($hinfo,true);
		} else {
			$json = new json();
			$hotelinfo = $json->jsonDecode($hinfo);
		}
		$hotelinfo = $hotelinfo['Hotel'];
		
		$param = array(
			'hotelCode' => $hotelCode,
			'roomCode' => $roomCode,
			'roomRatePlan' => $roomRatePlan,
			'checkInDate' => $checkInDate,
			'checkOutDate' => $checkOutDate,
			'arrivalEarlyTime' => $arrivalEarlyTime,
			'arrivalLateTime' => $arrivalLateTime,
			'note' => urlencode($note),
			'roomCount' => $roomCount,
			'guest' => urlencode($guest),
			'contacterName' => urlencode($contacterName),
			'contacterMobile' =>  $contacterMobile,
			'contacterEMail' => $contacterEMail,
			'isGuaranteeable' => $isGuaranteeable,
			'ccHolderName' => urlencode($ccHolderName),
			'ccNumber' => $ccNumber,
			'ccValidYear' => $ccValidYear,
			'ccValidMonth' => $ccValidMonth,
			'ccVeryfyCode' => $ccVeryfyCode,
			'ccIdTypeCode' => $ccIdTypeCode,
			'ccIdNumber' => $ccIdNumber
		);
		$resubmit = $this->hotelsubmitorder($param);
		if(!$resubmit || !is_array($resubmit)) {
			$logurl = admin_ROOT . 'datacache/log/';
			if (!is_dir($logurl)) {
				if (!@mkdir($logurl, 0777, true)) return false;
			}
			
			$logfile = $logurl . "orderlog_".date("Ymd").".txt";
			$result  = "\t\n\t\n=============================================\t\n";
			$result .= "datetime：".date('Y-m-d H:i:s')."\t\n";
			$result .= "return：".serialize($resubmit);

			$fp = fopen($logfile,"a"); 
			flock($fp, LOCK_EX) ;
			fwrite($fp,iconv('utf-8','gbk', $result)."\t\n");
			flock($fp, LOCK_UN); 
			fclose($fp);
			
			$ch['code'] = -1;
			$ch['message'] = "对不起，请求服务器失败，具体详情请与我们客服联系，客服电话：".$this->CON['ordertel'];
			$resstr = "";
			if($isjson) {
				$resstr = json_encode($ch);
			} else {
				$json = new json();
				$resstr = $json->jsonEncode($ch);
			}
			echo $resstr;
			exit;
		}
		if($resubmit['Status'] == 0) {
			$re = $resubmit['ResponseBody'];
		}
		$UserId = 0;
		$regMember = false;
		if($reg == "yes") {
			$regMember = true;
		}
		$check = parent::member_purview_ajax(1, null, true);
		$username = $this->ec_member_username;
		$uid = $this->ec_member_username_id;
		if($uid && $username) {
			$UserId = $uid;
		} else {
			if($regMember) {
				$lockusername = explode(',', $this->CON['mem_lock']);
				$db_table2 = db_prefix . "member";
				$db_where = " WHERE username='$contacterMobile'";
				$arruser = $this->db->fetch_first("SELECT `userid` FROM $db_table2 $db_where limit 1");
				$ipadd = $this->fun->ip($_SERVER['REMOTE_ADDR']);
				$addtime = time();
				$isclass = ($this->CON['mem_isemail']) ? 2 : 1;
				if(!$arruser) {
					if (!in_array($contacterMobile, $lockusername)) {
						$password = mt_rand(10000000, 99999999);;
						$password2 = md5($password);
						$db_field = 'username,password,email,question,answer,sex,birthday,country,province,city,district,alias,address,zipcode,tel,mobile,qq,msn,integral,visitcount,lastip,addtime,lasttime,mcid,isclass';
						$db_values = "'$contacterMobile','".$password2."','$contacterEMail','','',0,0,0,0,0,0,'$contacterName','',0,'','$contacterMobile',0,'',0,0,$ipadd,$addtime,$addtime,1,$isclass";
						$this->db->query('INSERT INTO ' . $db_table2 . ' (' . $db_field . ') VALUES (' . $db_values . ')');
						$insert_id = $this->db->insert_id();
						$UserId = $insert_id;
						$this->membersmssend('memberregsms',$contacterMobile,$password); //手机短信
					}
				} else {
					$UserId = $arruser['userid'];
				}
			} else {
				$db_table2 = db_prefix . "member";
				$db_where = " WHERE username='$contacterMobile'";
				$arruser = $this->db->fetch_first("SELECT `userid` FROM $db_table2 $db_where limit 1");
				if($arruser) {
					$UserId = $arruser['userid'];
				}
			}
		}
		$HotelOrderId = $re['HotelOrderId'];
		$CancellationTime = $re['CancellationTime']; //订单最晚取消时间
		$GuaranteeMoney = $re['GuaranteeMoney'];  //担保金额 非担保酒店显示为0
		
		$arrrooms = $hotelinfo['Rooms'];
		foreach ($arrrooms as $key=>$value) {
			if($value['TypeId'] == $roomCode) {
				$RoomTypeInfo = str_replace("免费","",$value['Note']).";房间面积：".$value['Area']."平方米;楼层：".$value['Floor']."层；说明：".$value['RatePlans'][0]['Name'];
			}
		}
		$GuestAmount = explode(",",$guest);
		$guestarr = $contacter = array();
		$guestarr = array(
            'Name' => str_replace(",","/",$guest),
            'GenderCode' => 2,
            'Email' => '',
            'Mobile' => '',
            'IdTypeCode' => '',
            'IdNumber' => '',
            'Nationality' => '',
            'Phone' => '',
            'Fax' => ''
        );
        $Guests_Guest = addslashes(serialize($guestarr));
        $Guest_Name = str_replace(",","/",$guest);
        $Guest_Mobile = $contacterMobile;
        $contacter = array(
            'Name' => $contacterName,
            'GenderCode' => 2,
            'Email' => $contacterEMail,
            'Mobile' => $contacterMobile,
            'IdTypeCode' => '',
            'IdNumber' => '',
            'Phone' => '',
            'Fax' => ''
        );
		$Contacters_Contacter = addslashes(serialize($contacter));
		$Contacter_Name = $contacterName;
		$Contacter_Mobile = $contacterMobile;
		$credit = array();
		$credit = array(
			'Number'=>$ccNumber,
			'VeryfyCode'=>$ccVeryfyCode,
			'ValidYear'=>$ccValidYear,
			'ValidMonth'=>$ccValidMonth,
			'CardHolderName'=>$ccHolderName,
			'IdTypeCode'=>$ccIdTypeCode,
			'IdNumber'=>$ccIdNumber
		);
		$CreditCard = addslashes(serialize($credit));
		$arrcityid = array();
		$arrcityid = $this->get_convercity($hotelinfo['ProvinceId'],$hotelinfo['CityId'],$hotelinfo['DistrictId']);
        
		$dbparam = array(
			'UserId' => $UserId,
			'OrderType' => 1,
			'HotelOrderID' => $HotelOrderId,
			'OrderState' => 1,
			'IsIntegral' => 0,
			'OrderDatetime' => time(),
			'HotelName' => $hotelinfo['Name'],
			'HotelinProvince' => $arrcityid[0],  //酒店所属城市需加上
			'HotelinCity' => $arrcityid[1],
			'HotelinArea' => $arrcityid[2],
			'HotelAddr' => $hotelinfo['Address'],
			'HotelinCompany' => 1,
			'HotelMembers' => 0,
			'HotelStar' => $hotelinfo['Category'],
			'HotelId' => $hotelCode,
			'RoomTypeId' => $roomCode,
			'RatePlanID' => $roomRatePlan,
			'RoomTypeName' => $hotelinfo['Rooms'][0]['Name'],
			'RoomTypeInfo' => $RoomTypeInfo,
			'RoomPrice' => $firstNightFees,
			'CheckInDate' => strtotime($checkInDate),
			'CheckOutDate' => strtotime($checkOutDate),
			'RoomAmount' => $roomCount,
			'GuestAmount' => count($GuestAmount),
			'ArrivalEarlyTime' => strtotime($checkInDate." ".$arrivalEarlyTime),
			'ArrivalLateTime' => strtotime($checkInDate." ".$arrivalLateTime),
			'TotalPrice' => $allfullfees,
			'ConfirmTypeCode' => 'sms',
			'CurrencyCode' => 'RMB',
			'NoteofGuest' => $note,
			'Contacters_Contacter' => $Contacters_Contacter,
			'Contacter_Name' => $Contacter_Name,
			'Contacter_Mobile' => $Contacter_Mobile,
			'CreditCard' => $CreditCard,  //需要加上
			'Guests_Guest' => $Guests_Guest,
			'Guest_Name' => $Guest_Name,
			'Guest_Mobile' => $Guest_Mobile,
		);
		$db_table = db_prefix . 'hotel_order';
		if($resubmit['Status'] == 0 || $resubmit['Status'] == 3)  { //0 和3状态 入库
			$orderid = $this->inserttable($db_table,$dbparam,1);
		}
		if($resubmit['Status'] > 0) {  //大于0记录日志
			$logurl = admin_ROOT . 'datacache/log/';
			if (!is_dir($logurl)) {
				if (!@mkdir($logurl, 0777, true)) return false;
			}
			$param['note'] = urldecode($param['note']);
			$param['guest'] = urldecode($param['guest']);
			$param['contacterName'] = urldecode($param['contacterName']);
			$param['ccHolderName'] = urldecode($param['ccHolderName']);
			$logfile = $logurl . "orderlog_".date("Ymd").".txt";
			$result  = "\t\n\t\n=============================================\t\n";
			$result .= "datetime：".date('Y-m-d H:i:s')."\t\n";
			$result .= "param：".serialize($param)."\t\n";
			$result .= "return：".serialize($resubmit);

			$fp = fopen($logfile,"a"); 
			flock($fp, LOCK_EX) ;
			fwrite($fp,iconv('utf-8','gbk', $result)."\t\n");
			flock($fp, LOCK_UN); 
			fclose($fp);

			$res['code'] = -2;
			$err = "";
			for($i=0;$i<count($resubmit['Messages']);$i++) {
				if($i<(count($resubmit['Messages'])-1)) {
					$err .= $resubmit['Messages'][$i] . "\r\n";
				} else {
					$err .= $resubmit['Messages'][$i];
				}
			}
			$err = str_replace("400-680-8722",$this->CON['ordertel'],$err);
			$res['message'] = $err;
			$jsonstr = "";
			if($isjson) {
				$jsonstr = json_encode($res);
			} else {
				$json = new json();
				$jsonstr = $json->jsonEncode($res);
			}
			echo $jsonstr;
			exit;
		}
		$ch = array();
		$res = array();
		if($orderid > 0) {
			$ch['code'] = 1;
			$ch['message'] = $re;
			$resstr = "";
			if($isjson) {
				$resstr = json_encode($ch);
			} else {
				$json = new json();
				$resstr = $json->jsonEncode($ch);
			}
			echo $resstr;
			exit;
		} else {
			$ch['code'] = -1;
			$ch['message'] = "提交数据失败，请与我们客服联系";
			$resstr = "";
			if($isjson) {
				$resstr = json_encode($ch);
			} else {
				$json = new json();
				$resstr = $json->jsonEncode($ch);
			}
			echo $resstr;
			exit;
		}
	}
	//担保信息
	function in_hotelgaranteerule() {
		include_once admin_ROOT . 'public/class_json.php';
		$isjson = function_exists('json_decode')? true : false;
		if($isjson) {
			$rule = json_decode(stripslashes(html_entity_decode($this->fun->accept('rule', 'R'))),true);
		} else {
			$json = new json();
			$rule = $json->jsonDecode(stripslashes(html_entity_decode($this->fun->accept('rule', 'R'))));
		}
		$hotelCode = $this->fun->accept('hid', 'R'); 
		$roomCode = $this->fun->accept('rid', 'R'); 
		$roomRatePlan = $this->fun->accept('pid', 'R'); 
		$checkInDate = $this->fun->accept('tm1', 'R'); 
		$checkOutDate = $this->fun->accept('tm2', 'R'); 
		$roomCount = $this->fun->accept('roomnum', 'R'); 
		$allfullfees = $this->fun->accept('allfullfees', 'R'); 
		$firstNightFees = $this->fun->accept('firstNightFees', 'R');
		$arriveTime = $this->fun->accept('arriveTime', 'R');   //到达酒店时间
		$bookingDate = time();
		
		$checkguarantee = '';
		$checkguarantee = $this->getgaranteerule($rule, $bookingDate, strtotime($checkInDate), $arriveTime, $roomCount, $firstNightFees, $allfullfees);
		echo $checkguarantee;
		exit;
	}
	

	function in_orderpay() {
		parent::start_pagetemplate();
		parent::member_purview(0, $this->mlink['orderpay']);
		$lng = (admin_LNG == 'big5') ? $this->CON['is_lancode'] : admin_LNG;
		$cartid = $this->fun->accept('ecisp_order_list', 'C');
		$cartid = stripslashes(htmlspecialchars_decode($cartid));
		$uncartid = !empty($cartid) ? unserialize($cartid) : 0;

		if (!empty($this->ec_member_username_id) && !empty($this->ec_member_username)) {

			$rsMember = $this->get_member(null, $this->ec_member_username_id);
		} else {

			$linkURL = $this->get_link('memberlogin');
			$this->callmessage($this->lng['memberloginerr'], $linkURL, $this->lng['memberlogin'], 1, $this->lng['member_regbotton'], 1, $this->mlink['reg']);
		}

		if ($uncartid && is_array($uncartid)) {
			$didarray = $this->fun->key_array_name($uncartid, 'did', 'amount');
			$didlist = $this->fun->format_array_text(array_keys($didarray), ',');
			if (!empty($didlist)) {
				$db_table = db_prefix . 'document';
				$db_where = "isclass=1 AND isorder=1 AND did in($didlist) ORDER BY did DESC";
				$sql = "SELECT did,lng,pid,mid,aid,tid,sid,fgid,linkdid,isclass,islink,ishtml,ismess,isorder,purview,recommend,tsn,title,longtitle,
					color,author,source,pic,link,oprice,bprice,click,addtime,template,filename,filepath FROM $db_table WHERE $db_where";
				$rs = $this->db->query($sql);

				$productmoney = 0;
				while ($rsList = $this->db->fetch_assoc($rs)) {
					$rsList['link'] = $this->get_link('doc', $rsList, admin_LNG);
					$rsList['buylink'] = $this->get_link('buylink', $rsList, admin_LNG);
					$rsList['enqlink'] = $this->get_link('enqlink', $rsList, admin_LNG);

					$rsList['dellink'] = $this->get_link('buydel', $rsList, admin_LNG);
					$rsList['ctitle'] = empty($rsList['color']) ? $rsList['title'] : "<font color='" . $rsList['color'] . "'>" . $rsList['title'] . "</font>";
					$rsList['amount'] = $didarray[$rsList['did']];

					$countprice = sprintf("%01.2f", $didarray[$rsList['did']] * $rsList['bprice']);
					$rsList['countprice'] = $countprice;

					$productmoney = $productmoney + $countprice;
					$array[] = $rsList;
				}

				$this->fun->setcookie('ecisp_order_productmoney', $productmoney, 7200);
			}

			$this->pagetemplate->assign('moneytype', $this->CON['order_moneytype']);

			$order_discount = $this->CON['order_discount'];
			$discountmoney = 0;
			if ($order_discount > 0) {

				$discountmoney = $productmoney > 0 ? $productmoney - ($order_discount / 100) * $productmoney : 0;
			}

			$discount_productmoney = $productmoney - $discountmoney;
			$payplug = $this->get_payplug_array($this->CON['order_pay']);
			$shipplug = $this->get_shipplug_array($this->CON['order_shipping']);

			$cookiceprice = md5("$productmoney|$discount_productmoney");
			$this->fun->setcookie('ecisp_order_sncode', $this->fun->eccode($cookiceprice, 'ENCODE', db_pscode));

			$this->pagetemplate->assign('discount', $order_discount);

			$this->pagetemplate->assign('productmoney', $productmoney);

			$this->pagetemplate->assign('discount_productmoney', $discount_productmoney);

			$this->pagetemplate->assign('discountmoney', $discountmoney);
			$this->pagetemplate->assign('discount_productmoney_f', number_format($discount_productmoney, 2, '.', ','));
			$this->pagetemplate->assign('productmoney_f', number_format($productmoney, 2, '.', ','));
			$this->pagetemplate->assign('discountmoney_f', number_format($discountmoney, 2, '.', ','));
			$this->pagetemplate->assign('payplug', $payplug['list']);
			$this->pagetemplate->assign('shipplug', $shipplug['list']);
			$this->pagetemplate->assign('array', $array);
		} else {
			$buylink = $this->get_link('order', array(), admin_LNG);
			$this->callmessage($this->lng['order_nolist'], $buylink, $this->lng['oder_buy_goback']);
		}
		$this->pagetemplate->assign('mlink', $this->mlink);
		$this->pagetemplate->assign('member', $rsMember);
		$this->pagetemplate->assign('path', 'order');

		$templatesDIR = $this->get_templatesdir('order');

		$templatesDIR = $this->get_templatesdir('order');
		$templatefilename = $lng . '/' . $templatesDIR . '/order_buy_center';
		$this->pagetemplate->assign('out', 'buyedit');
		unset($array, $this->mlink, $LANPACK, $this->lng);
		$this->pagetemplate->display($templatefilename, 'order_list', false, '', admin_LNG);
	}

	function in_ordersave() {
		parent::start_pagetemplate();
		parent::member_purview(0, $this->mlink['orderpay']);
		$lng = (admin_LNG == 'big5') ? $this->CON['is_lancode'] : admin_LNG;
		$cartid = $this->fun->accept('ecisp_order_list', 'C');
		$cartid = stripslashes(htmlspecialchars_decode($cartid));
		$uncartid = !empty($cartid) ? unserialize($cartid) : 0;

		$ordersncode = $this->fun->accept('ecisp_order_sncode', 'C');

		$userid = intval($this->fun->accept('userid', 'P'));
		$consignee = trim($this->fun->accept('alias', 'P', true, true));
		$email = $this->fun->accept('email', 'P');
		$country = intval($this->fun->accept('cityone', 'P'));
		$province = intval($this->fun->accept('citytwo', 'P'));
		$city = intval($this->fun->accept('citythree', 'P'));
		$district = intval($this->fun->accept('district', 'P'));
		$address = trim($this->fun->accept('address', 'P', true, true));
		$zipcode = trim($this->fun->accept('zipcode', 'P', true, true));
		$tel = trim($this->fun->accept('tel', 'P', true, true));
		$mobile = trim($this->fun->accept('mobile', 'P', true, true));
		$sendtime = $this->fun->accept('sendtime', 'P');
		$content = trim($this->fun->accept('content', 'P', true, true));
		$invpayee = trim($this->fun->accept('invpayee', 'P', true, true));
		$invcontent = trim($this->fun->accept('invcontent', 'P', true, true));

		$opid = intval($this->fun->accept('opid', 'P'));

		$osid = intval($this->fun->accept('osid', 'P'));

		$productmoney = $this->fun->accept('productmoney', 'P');

		$discount_productmoney = $this->fun->accept('discount_productmoney', 'P');
		$discountmoney = $this->fun->accept('discountmoney', 'P');
		$cookiceprice = $this->fun->eccode(md5("$productmoney|$discount_productmoney"), 'ENCODE', db_pscode);
		if ($uncartid && is_array($uncartid) && !empty($ordersncode) && $cookiceprice == $ordersncode) {
			$ptitle = $this->fun->accept('ptitle', 'P');
			$tsn = $this->fun->accept('tsn', 'P');
			$bprice = $this->fun->accept('bprice', 'P');
			$oprice = $this->fun->accept('oprice', 'P');
			$did = $this->fun->accept('did', 'P');
			$amount = $this->fun->accept('amount', 'P');
			$countprice = $this->fun->accept('countprice', 'P');
			if (empty($did) || empty($bprice) || empty($amount) || empty($countprice) || empty($opid) || empty($osid)) {
				$buylink = $this->get_link('order', array(), admin_LNG);
				$this->callmessage($this->lng['order_input_err'], $buylink, $this->lng['oder_buy_goback']);
			}
			if (!preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/i", $email)) {
				$this->callmessage($this->lng['email_err'], $_SERVER['HTTP_REFERER'], $this->lng['gobackbotton']);
			}

			$payprice = 0;
			$shipprice = 0;

			$payread = !empty($opid) ? $this->get_payplug_view($opid) : 0;

			$shipprice = !empty($osid) ? $this->get_shipplug_view($osid, 'price') : 0;
			if ($payread['payis'] > 0) {

				$payprice = ($payread['payis'] / 100) * $discount_productmoney;
			}

			$orderamount = $discount_productmoney + $payprice + $shipprice;

			$order_snfont = $this->CON['order_snfont'];
			$ordersn = $order_snfont . date('YmdHis') . rand(100, 9999);

			$db_table = db_prefix . 'order';
			$db_table2 = db_prefix . 'order_info';
			$addtime = time();
			$db_field = 'ordersn,userid,ordertype,osid,opid,shippingsn,paysn,consignee,country,province,city,district,address,
				zipcode,tel,mobile,email,sendtime,invpayee,invcontent,content,treatnote,paytime,shippingtime,productmoney,shippingmoney,
				paymoney,orderamount,discount,integral,addtime';
			$db_values = "'$ordersn',$userid,1,$osid,$opid,'','','$consignee',$country,$province,$city,$district,'$address',
				'$zipcode','$tel','$mobile','$email','$sendtime','$invpayee','$invcontent','$content','',0,0,$productmoney,$shipprice,
				$payprice,$orderamount,$discountmoney,0,$addtime";
			$this->db->query('INSERT INTO ' . $db_table . ' (' . $db_field . ') VALUES (' . $db_values . ')');
			$insert_id = $this->db->insert_id();

			$db_values = '';
			$arraycount = count($did) - 1;
			foreach ($did as $key => $value) {
				if ($key == $arraycount) {
					$db_values.= "($insert_id,$value,'$tsn[$key]','$ptitle[$key]',$oprice[$key],$bprice[$key],$countprice[$key],$amount[$key],1)";
				} else {
					$db_values.= "($insert_id,$value,'$tsn[$key]','$ptitle[$key]',$oprice[$key],$bprice[$key],$countprice[$key],$amount[$key],1),";
				}
			}
			$db_field = 'oid,did,tsn,title,oprice,bprice,countprice,amount,inventory';
			$this->db->query('INSERT INTO ' . $db_table2 . ' (' . $db_field . ') VALUES ' . $db_values);

			if ($this->CON['is_email'] == 1) {

				$this->ordermailsend('orderen', $insert_id);

				$this->ordermailsend('orderwarn', $insert_id);
			}
			if (!empty($opid)) {

				$rsOrder = array('ordersn' => $ordersn, 'orderamount' => $orderamount, 'oid' => $insert_id);

				$paylist = $this->fun->formatarray($payread['pluglist']);
				$plugcode = $payread['paycode'];

				if (!empty($plugcode)) {

					include_once admin_ROOT . 'public/plug/payment/' . $plugcode . '.php';

					$payobj = new $plugcode();
					$codesn = $this->fun->eccode($plugcode . $ordersn . $insert_id, 'ENCODE', db_pscode);
					$respondArray = array('code' => $plugcode, 'ordersn' => $ordersn, 'oid' => $insert_id, 'codesn' => $codesn);

					$return_url = $this->get_link('paybackurl', $respondArray, admin_LNG);

					$orderonline = $payobj->get_code($rsOrder, $paylist, $return_url, $return_url);
				}
			}
			$this->pagetemplate->assign('mlink', $this->mlink);
			$this->pagetemplate->assign('orderonline', $orderonline);

			$this->pagetemplate->assign('ordersn', $ordersn);

			$this->pagetemplate->assign('orderamount', number_format($orderamount, 2));

			$this->pagetemplate->assign('payprice', number_format($payprice, 2));

			$this->pagetemplate->assign('shipprice', number_format($shipprice, 2));

			$this->pagetemplate->assign('discount', number_format($discount_productmoney, 2));

			$this->pagetemplate->assign('productmoney', number_format($productmoney, 2));

			$this->pagetemplate->assign('discountmoney', number_format($discountmoney, 2));

			$this->pagetemplate->assign('moneytype', $this->CON['order_moneytype']);

			$this->fun->setcookie('ecisp_order_list', null);
			$this->fun->setcookie('ecisp_order_productmoney', null);

			$templatesDIR = $this->get_templatesdir('order');
			$templatefilename = $lng . '/' . $templatesDIR . '/order_buy_center';
			$this->pagetemplate->assign('out', 'buyok');
			$this->pagetemplate->assign('path', 'order');
			unset($this->mlink, $LANPACK, $this->lng);
			$this->pagetemplate->display($templatefilename, 'order_ok', false, '', admin_LNG);
		} else {
			$buylink = $this->get_link('order', array(), admin_LNG);
			$this->callmessage($this->lng['order_nolist'], $buylink, $this->lng['oder_buy_goback']);
		}
	}

	function in_orderupdae() {
		$bprice = $this->fun->accept('bprice', 'P');
		$didlist = $this->fun->accept('did', 'P');
		$amountlist = $this->fun->accept('amount', 'P');
		foreach ($didlist as $key => $value) {
			$arraykeyname = 'k' . $value;
			$amount = intval($amountlist[$key]);
			$orderlist[$arraykeyname] = array('did' => $value, 'amount' => $amount);
		}
		$orderlist_ser = serialize($orderlist);

		$this->fun->setcookie('ecisp_order_list', $orderlist_ser, 7200);
		$buylink = $this->get_link('order', array(), admin_LNG);
		$this->callmessage($this->lng['order_amout_updateok'], $buylink, $this->lng['oder_buy_goback']);
	}

	function in_delcart() {
		$did = intval($this->fun->accept('did', 'R'));
		if (empty($did)) trigger_error("Product parameter error!", E_USER_ERROR);
		$cartid = $this->fun->accept('ecisp_order_list', 'C');
		$cartid = stripslashes(htmlspecialchars_decode($cartid));
		$uncartid = !empty($cartid) ? unserialize($cartid) : 0;
		$arraykeyname = 'k' . $did;
		unset($uncartid[$arraykeyname]);
		$orderlist = serialize($uncartid);

		$this->fun->setcookie('ecisp_order_list', $orderlist, 7200);
		$buylink = $this->get_link('order', array(), admin_LNG);
		$this->callmessage($this->lng['order_delcartok'], $buylink, $this->lng['oder_buy_goback']);
	}

	function in_clearcart() {
		$this->fun->setcookie('ecisp_order_list', null);
		$this->fun->setcookie('ecisp_order_productmoney', null);
		$buylink = $this->get_link('order', array(), admin_LNG);
		$this->callmessage($this->lng['order_clearcart'], $buylink, $this->lng['oder_buy_goback']);
	}

}
?>
